package com.leyou.item.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品规格业务
 */
@Service
@Transactional
public class SpecService {
    @Autowired
    private SpecGroupMapper specGroupMapper;
    @Autowired
    private SpecParamMapper specParamMapper;

    public List<SpecGroup> findSpecGroupsByCid(Long id) {
        //1.封装条件
        SpecGroup specGroup = new SpecGroup();
        specGroup.setCid(id);

        QueryWrapper<SpecGroup> queryWrapper = Wrappers.query(specGroup);

        //2.执行查询
        List<SpecGroup> specGroups = specGroupMapper.selectList(queryWrapper);

        //3.处理结果
        if(CollectionUtils.isEmpty(specGroups)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }

        //4.返回结果
        return specGroups;
    }

    public List<SpecParam> findSpecParams(Long gid, Long cid, Boolean searching) {
        //1.封装条件
        SpecParam specParam = new SpecParam();
        //注意：MyBatisPlus会自动判断该属性如果为NULL，则不作为查询条件
        specParam.setGroupId(gid);
        specParam.setCid(cid);
        specParam.setSearching(searching);

        QueryWrapper<SpecParam> queryWrapper = Wrappers.query(specParam);

        //2.执行查询
        List<SpecParam> specParams = specParamMapper.selectList(queryWrapper);

        //3.处理结果
        if(CollectionUtils.isEmpty(specParams)){
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }

        //4.返回结果
        return specParams;
    }

    public List<SpecGroupDTO> findSpecGroupParamsByCid(Long id) {
        try {
            //1.根据分类id查询规格组
            List<SpecGroup> specGroups = this.findSpecGroupsByCid(id);
            //2.把List<SpecGroup>拷贝成为List<SpecGroupDTO>
            List<SpecGroupDTO> specGroupDTOS = BeanHelper.copyWithCollection(specGroups, SpecGroupDTO.class);
            //3.遍历集合，分别查询组内参数并封装
            specGroupDTOS.forEach(specGroupDTO -> {
                //根据规格组id查询组内参数
                List<SpecParam> specParams = this.findSpecParams(specGroupDTO.getId(), null, null);
                specGroupDTO.setParams(specParams);
            });
            return specGroupDTOS;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
    }
}
